import { Component, ElementRef, Renderer2 } from '@angular/core';

import { ViewChild } from "@angular/core"

@Component({
  selector: 'app-page-introduce',
  templateUrl: './page-introduce.component.html',
  styleUrls: ['./page-introduce.component.scss']
})

export class PageIntroduceComponent {
  @ViewChild("moveBody") moveBody:ElementRef | undefined
  @ViewChild("moveContainer") moveContainer:ElementRef | undefined
  startX: number = 0;
  startY: number = 0;

  constructor(private renderer: Renderer2) {}

  ngAfterViewInit() {
    
    this.scrollToCenter()
  }

  /**
   * 可移动区域默认从中央显示
   */
  scrollToCenter(){
    setTimeout(() => {
        if(this.moveBody?.nativeElement){
          this.moveBody.nativeElement.scrollLeft = this.moveContainer?.nativeElement.clientWidth/2 - this.moveBody.nativeElement.clientWidth/2
          this.moveBody.nativeElement.scrollTop = this.moveContainer?.nativeElement.clientHeight/2 - this.moveBody.nativeElement.clientHeight/2
        }
      }, 10);
  }

  onDragStart(event: TouchEvent) {
    // 阻止默认事件
    event.preventDefault();

    const touch = event.touches[0];
    const draggableElement = touch.target as HTMLElement;

    // 记录初始位置
    this.startX = touch.clientX;
    this.startY = touch.clientY;

    // 添加事件监听器
    this.renderer.listen('window', 'touchmove', (event) => {
      this.onDragMove(event);
    });
    this.renderer.listen('window', 'touchend', (event) => {
      this.onDragEnd(event);
    });
  }

  onDragMove(event: TouchEvent) {
    const touch = event.touches[0];
    const draggableElement = touch.target as HTMLElement;

    // 计算移动距离
    const offsetX = touch.clientX - this.startX;
    const offsetY = touch.clientY - this.startY;

    // 应用移动
    draggableElement.style.transform = `translate(${offsetX}px, ${offsetY}px)`;
  }

  onDragEnd(event: TouchEvent) {
    // 移除事件监听器
    this.renderer.listen('window', 'touchmove', this.onDragMove);
    this.renderer.listen('window', 'touchend', this.onDragEnd);
  }
}


